﻿<%@ WebHandler Language="C#" Class="GetObject" %>
using System.Linq;
using System.Web;

public class GetObject : IHttpHandler {
    
    public void ProcessRequest(HttpContext context) {
        int id;
        if (int.TryParse(context.Request.Params["ID"], out id))
        {
            context.Response.Clear();
            context.Response.BufferOutput = true;

            using (var c = DBUtils.CreateDataAbstaction())
            {
                var mo = c.MObjects.Single(m => m.ID == id);
                switch (mo.Type)
                {
                    case 0:
                        context.Response.ContentType = "image/JPEG";
                        break;
                        
                    default:
                        throw new HttpException(string.Format("Invalid type of media object: {0}", mo.Type));
                }
                
                if (mo.Data != null)
                {
                    context.Response.BinaryWrite(mo.Data);
                }                
                context.Response.StatusCode = 200;
                context.Response.End();
                return;
            }
        }
        
        throw new HttpException("Cannot find requested data");

    }


    public bool IsReusable { get { return true; } }
}